package com.study_security.service.impl;

import com.study_security.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

@Service
public class EmailService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sender;

    @Value("${spring.mail.nickname}")
    private String nickname;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.port}")
    private int port;

    @Value("${spring.mail.password}")
    private String password;

    private void configureMailSender() {
        if (mailSender instanceof JavaMailSenderImpl) {
            JavaMailSenderImpl mailSenderImpl = (JavaMailSenderImpl) mailSender;
            mailSenderImpl.setHost(host);
            mailSenderImpl.setPort(port);
            mailSenderImpl.setUsername(sender);
            mailSenderImpl.setPassword(password);

            Properties props = mailSenderImpl.getJavaMailProperties();
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.debug", "true");
        }
    }

    public void sendVerificationCode(String to, String code) {
        configureMailSender();

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(nickname + '<' + sender + '>');
        message.setTo(to);
        message.setSubject("Your Verification Code");
        message.setText("Your verification code is: " + code + ". The code is valid for 5 minutes.");

        mailSender.send(message);
    }

    public void saveVerificationCode(String email, String code) {
        redisCache.setCacheObject("verify:email:" + email, code, 5, TimeUnit.MINUTES);

    }
}
